package bloggo

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path"
)

//路径常量
const (
	// AVATAR 头像路径
	PATH_AVATAR = "avatar/"
	// ARTICLE 文章图片路径
	PATH_ARTICLE = "articles/"
	// VOICE 音频路径
	PATH_VOICE = "voice/"
	// PHOTO 照片路径
	PATH_PHOTO = "photos/"
	// CONFIG 配置图片路径
	PATH_CONFIG = "config/"
)

// UploadFile 文件上传 返回文件的访问链接
func UploadFile(r *http.Request, requestFileName string, savePath string) string {
	if requestFileName == "" {
		requestFileName = "file"
	}
	readFile, multipart, err := r.FormFile(requestFileName)
	if err != nil {
		panic(err)
	}
	defer readFile.Close()
	if multipart.Size > Conf.Upload.MaxSize*1024*1024 {
		panic(fmt.Sprint("文件大小超出限制,[fileSize<", Conf.Upload.MaxSize, "MB]"))
	}
	data, err := ioutil.ReadAll(readFile)
	if err != nil {
		panic(err)
	}
	md5 := MD5(data)
	//扩展名
	ext := path.Ext(multipart.Filename)
	filename := md5 + ext
	err = os.MkdirAll(Conf.Upload.Path+savePath, 0666)
	if err != nil {
		panic(err)
	}
	exists, _ := pathExists(Conf.Upload.Path + savePath + filename)
	if exists {
		return Conf.Upload.Url + savePath + filename
	}
	err = ioutil.WriteFile(Conf.Upload.Path+savePath+filename, data, 0666)
	if err != nil {
		panic(err)
	}
	return Conf.Upload.Url + savePath + filename
}
func pathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func GetFileLinkPrefix() string {
	bytes := []byte(Conf.Upload.Url)
	var linkBytes []byte
	index := len(bytes) - 1
	for i := index; i >= 0; i-- {
		if i < index && bytes[i] == byte('/') {
			break
		}
		linkBytes = append(linkBytes, bytes[i])
	}
	le := len(linkBytes)
	for i := 0; i < le/2; i++ {
		temp := linkBytes[i]
		linkBytes[i] = linkBytes[le-i-1]
		linkBytes[le-i-1] = temp
	}
	return string(linkBytes)
}
